package xmw

import (
	"errors"
	"gitee.com/xiedongji/antgo/helper/xstring"
	"gitee.com/xiedongji/antgo/helper/xtoken"
	"gitee.com/xiedongji/antgo/helper/xutils"
	"github.com/gin-gonic/gin"
)

/* ============================================================ *
 * 功能:API鉴权
 * 类型:中间件
 * 举例: "/land/login","/land/logout", "/ping","/res/"
 * ============================================================ */
const (
	AuthKey    = "Authorization" // 请求头部关键字
	SessionKey = "session_key"   //
)

func ApiAuthMiddleware(allowUrls ...string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 默认允许的url
		if len(allowUrls) > 0 {
			if xstring.InArrayString(ctx.Request.URL.Path, allowUrls) ||
				xstring.InArrayPath(ctx.Request.URL.Path, allowUrls) {
				ctx.Next()
				return
			}
		}

		token := ctx.GetHeader(AuthKey)
		if token == "" {
			xutils.ResponseError(ctx, errors.New("登录标识丢失"))
			ctx.Abort()
			return
		}

		sessionInfo, err := xtoken.ParseToken(token)
		if err != nil {
			xutils.ResponseErrorCode(ctx, xutils.CodeUnLogin, err)
			ctx.Abort()
			return
		}

		if sessionInfo == nil {
			xutils.ResponseError(ctx, errors.New("登录信息解析失败"))
			ctx.Abort()
			return
		}

		if sessionInfo.UserName == "" || sessionInfo.UserId == 0 {
			xutils.ResponseError(ctx, errors.New("登录信息解析失败2"))
			ctx.Abort()
			return
		}

		// 设置登录信息
		ctx.Set(SessionKey, sessionInfo)

		ctx.Next()
	}
}
